package com.bestcem.xm.member.handler.imports;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSONArray;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.member.entity.pojo.ExtendFieldEnumItemDO;
import com.bestcem.xm.member.enums.ImportRecordStatusEnum;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.enums.NewMemberStatusEnum;
import com.bestcem.xm.member.grpc.service.param.imports.ImportMembersParam;
import com.bestcem.xm.member.handler.imports.easyexcel.HttpReadInstitutionMemberListener;
import com.bestcem.xm.member.service.dto.FieldDTO;
import com.bestcem.xm.member.service.param.ImportMemberParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.bestcem.xm.member.constant.Constants.INSTITUTION_BASE_EXCEL_HEADERS;

/**
 * 机构联系人导入
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/7/20
 */
@Slf4j
@Component
public class InstitutionMemberImportHandler extends BaseImportHandle {

    @Override
    public String getTemplateExcelPath() {
        return "/file/excel/institutionImportTemplate.xlsx";
    }

    @Override
    public String getExcelTemplateName() {
        return "institutionImportTemplate.xlsx";
    }

    /**
     * 机构联系人表头 扩展字段
     *
     * @param orgId
     * @return
     */
    @Override
    public List<String> getHeader(String orgId) {
        // 获取该组织下所有的扩展字段
        List<String> fieldNames = getFieldNames(orgId, MemberTypeEnum.INSTITUTION.getIndex());
        int size = INSTITUTION_BASE_EXCEL_HEADERS.size() + fieldNames.size();
        List<String> headers = new ArrayList<>(size);
        // 机构联系人基础字段
        headers.addAll(INSTITUTION_BASE_EXCEL_HEADERS);
        // 扩展字段
        headers.addAll(fieldNames);
        return headers;
    }

    @Override
    public List<String> getExcelHeaders() throws IOException {
        return getTemplateHeaders(getTemplateExcelPath());
    }

    @Override
    public String genImportLockKey(String orgId) {
        return "member.memberNo." + orgId + "institution";
    }

    @Override
    public ServiceResult<String> importMemberExcel(ImportMembersParam param) {

        if (param.getImportType() == 1) {
            // 覆盖导入
            // 删除该组织下所有的相关联系人
            getMemberDao().updateStatusByOrgIdAndAttribute(NewMemberStatusEnum.MEMBER_STATUS_SOFT_DELETE.getIndex(),
                    param.getOrgId(), param.getAttribute());
        }
        // return importMemberFromExcel(param);
        return null;
    }

//    private ServiceResult<String> importMemberFromExcel(ImportMembersParam param) {
//        JSONObject totalErrorMsgJson = new JSONObject();
//        // 获取扩展字段映射
//        Map<String, FieldDTO> filedMap = getFiledMap(param.getOrgId(), 0);
//        // 获取所有的门店名和id的映射
//        Map<String, String> storeNameIdMap = getStoreNameIdMap(param.getOrgId());
//
//        // 联系人剩余数量
//        Long freeCount = null;
//        if (param.getIsFree()) {
//            Long memberNumber = getMemberNumber(param.getOrgId());
//            freeCount = FREE_USER_MEMBER_NUMBER - memberNumber;
//            if (freeCount <= 0) {
//                totalErrorMsgJson.set("0", "免费版限制联系人上传数量为100");
//                return ServiceResult.fail(totalErrorMsgJson.toString());
//            }
//
//        }
//        // 判断组织id是否有效
//        if (!checkOrganization(param.getOrgId())) {
//            totalErrorMsgJson.set("0", "公司不存在");
//            return ServiceResult.fail(totalErrorMsgJson.toString());
//        }
//
//        ExcelReader excelReader = null;
//        ReadIndividualMemberListener listener = new ReadIndividualMemberListener();
//        try {
//            excelReader = EasyExcel.read(param.getFileUrl()).build();
//            listener.setFieldMap(filedMap);
//            listener.setParam(param);
//            listener.setFreeCount(freeCount);
//            listener.setStoreNameIdMap(storeNameIdMap);
//            listener.setMemberService(getMemberService());
//            listener.setImportService(getImportService());
//            ReadSheet readSheet = EasyExcel.readSheet().registerReadListener(listener).build();
//            excelReader.read(readSheet);
//        } catch (Exception e) {
//            log.error("文件导入出现未知错误，请检查文件格式及模板匹配度", e);
//
//        } finally {
//            if (excelReader != null) {
//                excelReader.finish();
//            }
//        }
//        return ServiceResult.success();
//    }

    @Override
    protected void importMemberExcel(ImportMemberParam param) {
        if (log.isInfoEnabled()) {
            log.info("【member】 开始异步导入...");
        }
        importExcel(param);
    }

    /**
     * 导入excel
     *
     * @param param
     */
    private void importExcel(ImportMemberParam param) {
        if (StrUtil.isNotEmpty(param.getPrimaryKey()) || param.getType() == 0) {
            // 增量导入
            incrementImportExcel(param);
        } else {
            // 全量导入
            overwriteImportExcel(param);
        }
    }

    /**
     * 全量覆盖导入
     *
     * @param param
     */
    private void overwriteImportExcel(ImportMemberParam param) {
        // 删除该组织下所有的相关类型的联系人
        memberDao.updateStatusByOrgIdAndAttribute(NewMemberStatusEnum.MEMBER_STATUS_SOFT_DELETE.getIndex(),
                param.getOrgId(), param.getAttribute());
        importIndMember(param);
    }

    /**
     * 增量导入
     *
     * @param param
     */
    private void incrementImportExcel(ImportMemberParam param) {
        importIndMember(param);
    }

    /**
     * 导入个人联系人
     *
     * @param param
     */
    private void importIndMember(ImportMemberParam param) {
        // 获取扩展字段map
        Map<String, FieldDTO> filedMap = getFiledMap(param.getOrgId(), param.getAttribute());
        param.setFiledMap(filedMap);
        // 获取扩展字段对应的枚举类型
        Map<String, List<ExtendFieldEnumItemDO>> extendFieldEnumMap = getExtendFieldEnumMap(filedMap);
        param.setExtendFieldEnumMap(extendFieldEnumMap);
        // 获取门店信息map
        Map<String, String> storeNameIdMap = getStoreNameIdMap(param.getOrgId());
        param.setStoreNameIdMap(storeNameIdMap);

        // 获取组织下联系人的数量
        Integer memberNumber = getMemberNumber(param.getOrgId(), param.getAttribute()).intValue();

        param.setMemberNumber(memberNumber);

        if (!checkOrganization(param.getOrgId())) {
            // 公司不存在
            throw new IllegalArgumentException("该组织不存在");
        }
        ExcelReader excelReader = null;
        //  easyExcel 读文件
        HttpReadInstitutionMemberListener listener = new HttpReadInstitutionMemberListener();
        try {
            excelReader = EasyExcel.read(param.getInputStream()).build();
            // memberService
            listener.setMemberService(memberService);
            // importService
            listener.setImportService(importService);
            // 是否获取过所有数量
            listener.setGetCount(false);
            // 是否终止读取excel
            listener.setIsStop(false);
            listener.setErrorMsgJsons(new JSONArray());
            listener.setParam(param);
            // 读取第一个sheet
            ReadSheet readSheet = EasyExcel.readSheet(0).registerReadListener(listener).build();
            excelReader.read(readSheet);
        } catch (Exception e) {
            log.error("文件导入异常", e);
            com.alibaba.fastjson.JSONObject totalErrorMsg = new com.alibaba.fastjson.JSONObject();
            JSONArray errorArray = new JSONArray();
            totalErrorMsg.put("-1", e.getMessage());
            errorArray.add(totalErrorMsg);
            Integer receiveCount = 0;
            Integer successCount = 0;
            Integer failedCount = totalErrorMsg.size();

            updateRecordData(param.getImportRecordId(), receiveCount, successCount, failedCount, errorArray, ImportRecordStatusEnum.IMPORT_RECORD_STATUS_FAILED.getIndex());
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
            if (param.getInputStream() != null) {
                try {
                    param.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 解锁
            removeLock(param.getKey());
            importService.deleteProgressBarStatus(0, param.getImportRecordId());
            if (log.isInfoEnabled()) {
                log.info("【member】异步导入完成...");
            }
        }
    }
}
